from decimal import Decimal
from datetime import datetime
from piecash import open_book, Transaction, Split, Account
from .gnucash_file_config import GNUCASH_PATH
from typing import List
import re

def get_accounts():
    """获取所有科目列表（过滤占位符）"""
    with open_book(GNUCASH_PATH, readonly=True) as book:
        return [
            acc.fullname for acc in book.accounts
            if not acc.placeholder  # 排除占位符科目
        ]

def add_transaction_from_dict(debit_name: str, credit_name: str,direction: int, transaction: dict) -> str|bool:
    with open_book(GNUCASH_PATH, readonly=False) as book:
        # 查找科目
        debit_acc = book.accounts.get(fullname=debit_name)
        credit_acc = book.accounts.get(fullname=credit_name)

        if not debit_acc or not credit_acc:
            return "错误: 科目不存在", 400
        
        if isinstance(transaction["amount"],str):
            amount=Decimal(re.search(r"[0-9]+\.[0-9]{2}",transaction["amount"]).group(0))

        if isinstance(transaction["date"],str):
            post_date=datetime.strptime(transaction["date"], "%Y年%m月%d日")
            # print(post_date)

        # 创建交易
        Transaction(
            currency=debit_acc.commodity,
            description=transaction["details"],
            enter_date=datetime.now(),
            post_date=post_date.date(),
            splits=[
                Split(account=debit_acc, value=direction*amount),
                Split(account=credit_acc, value=-direction*amount)
            ]
        )
        book.save()
    return True